<template>
  <n-layout has-sider>
    <!-- 左侧区域 -->
    <n-layout-sider bordered width="400" content-style="padding: 20px;">
      <n-space vertical>
        <n-input
          v-model:value="searchText"
          placeholder="搜索禁飞区"
          clearable
        />
        <n-data-table
          :columns="columns"
          :data="filteredAreas"
          :bordered="false"
        />
        <!-- 编辑操作按钮 -->
        <n-space v-if="isEditing">
          <n-button type="primary" @click="saveChanges">保留修改</n-button>
          <n-button type="error" @click="cancelChanges">取消修改</n-button>
        </n-space>
      </n-space>
    </n-layout-sider>

    <!-- 右侧地图区域 -->
    <n-layout-content>
      <div id="map-container" style="height: 500px;"></div>
    </n-layout-content>
  </n-layout>
</template>

<script setup>
import { ref, computed, h, onMounted, onBeforeUnmount } from 'vue'
import { NLayout, NLayoutSider, NLayoutContent, NInput, NSpace, NDataTable, NButton, useMessage } from 'naive-ui'
import { Map, View } from 'ol'
import { useGeographic } from 'ol/proj'
import XYZ from 'ol/source/XYZ'
import { Vector as VectorLayer } from 'ol/layer'
import TileLayer from 'ol/layer/Tile'
import { Vector as VectorSource } from 'ol/source'
import { Polygon } from 'ol/geom'
import { Style, Stroke, Fill, Text } from 'ol/style' // 导入Text样式
import { Modify } from 'ol/interaction'
import Feature from 'ol/Feature'
import Collection from 'ol/Collection' // 导入Collection类

// 使用地理坐标
useGeographic()

// 示例数据
const areas = ref([
  { 
    id: 1, 
    name: '机场禁飞区', 
    area: 50, 
    coordinates: [
      [30, 116],
      [20, 120],
      [12, 110]
    ] 
  },
  { 
    id: 2, 
    name: '军事禁区', 
    area: 100, 
    coordinates: [
      [27.77, 104.40],
      [28.58, 106.56],
      [28.61, 103.79]
    ] 
  },
  { 
    id: 3, 
    name: '禁飞区', 
    area: 80, 
    coordinates: [
      [29.5, 106.5],
      [29.5, 106.0],
      [29.0, 106.0],
      [29.0, 106.5]
    ] 
  },
  { 
    id: 4, 
    name: '科研实验区', 
    area: 120, 
    coordinates: [
      [31.2, 118.7],
      [30.8, 119.2],
      [30.5, 118.5],
      [30.9, 118.3]
    ] 
  },
  { 
    id: 5, 
    name: '大型活动区', 
    area: 90, 
    coordinates: [
      [26.4, 108.9],
      [26.6, 109.3],
      [26.2, 109.1]
    ] 
  },
  { 
    id: 6, 
    name: '核电站周边', 
    area: 150, 
    coordinates: [
      [32.1, 121.4],
      [31.9, 121.8],
      [31.7, 121.6],
      [31.8, 121.3]
    ] 
  }
])

const searchText = ref('')

// 过滤后的禁飞区列表
const filteredAreas = computed(() => {
  return areas.value.filter(area => 
    area.name.includes(searchText.value)
  )
})

// 表格列配置
const columns = [
  { title: '名称', key: 'name' },
  { title: '面积(km²)', key: 'area' },
  {
    title: '操作',
    key: 'actions',
    render(row) {
        const btns=[
            {title:'编辑',type:'info',fuc:() => handleEdit(row)}, // 绑定编辑事件
            {title:'删除',type:'Error',fuc:()=> handleDelete(row)}, // 绑定删除事件
          ]
          const btnsNode = btns.map((item)=>{
            return h(
              NButton,
              {type:item.type,onClick:item.fuc,style:{ margin:'5px'}},
              { default: () => item.title}
            )
          })
          return btnsNode
        }
    }
]

// 使用消息组件
const message = useMessage()

// 编辑状态
const isEditing = ref(false)
const editingFeature = ref(null)

// 编辑操作
const handleEdit = (row) => {
  const vectorSource = map.getLayers().getArray()[1].getSource()
  const features = vectorSource.getFeatures()
  const feature = features.find(f => f.get('name') === row.name)

  if (feature) {
    isEditing.value = true
    editingFeature.value = feature

    // 开启编辑功能
    modifyInteraction.setActive(true)
    modifyInteraction.setProperties({ features: new Collection([feature]) })

    // 提示用户
    message.info('已进入编辑模式，请拖动顶点进行修改')

    // 监听顶点变化
    feature.getGeometry().on('change', () => {
      const updatedCoordinates = feature.getGeometry().getCoordinates()[0]
      row.coordinates = updatedCoordinates.map(coord => [coord[1], coord[0]]) // 转换回[纬度, 经度]
      console.log('更新后的坐标:', row.coordinates)
    })
  }
}

// 保存修改
const saveChanges = () => {
  if (editingFeature.value) {
    const coordinates = editingFeature.value.getGeometry().getCoordinates()[0]
    console.log('保存的坐标:', coordinates)
    message.success('修改已保存')
    isEditing.value = false
    modifyInteraction.setActive(false)
  }
}

// 取消修改
const cancelChanges = () => {
  if (editingFeature.value) {
    message.warning('修改已取消')
    isEditing.value = false
    modifyInteraction.setActive(false)
  }
}

// 删除操作
const handleDelete = (row) => {
  // 实现删除逻辑
  message.warning('删除操作尚未实现，请联系杨敏大王')
  console.log('点击删除', row.name)
}

// 地图相关
let map = null
let modifyInteraction = null

const initMap = () => {
  const vectorSource = new VectorSource()
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style: (feature) => {
      return new Style({
        stroke: new Stroke({
          color: 'red',
          width: 2
        }),
        fill: new Fill({
          color: 'rgba(255, 0, 0, 0.2)'
        }),
        text: new Text({
          text: feature.get('name'),
          font: '14px sans-serif',
          fill: new Fill({
            color: '#000'
          }),
          stroke: new Stroke({
            color: '#fff',
            width: 2
          }),
          offsetY: -20
        })
      })
    }
  })

  map = new Map({
    target: 'map-container',
    layers: [
      new TileLayer({
        source: new XYZ({
          url: 'https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
          attributions: '© 高德地图'
        })
      }),
      vectorLayer
    ],
    view: new View({
      center: [104.09, 30.64],
      zoom: 5
    })
  })

  // 添加顶点编辑功能
  modifyInteraction = new Modify({
    source: vectorSource
  })
  modifyInteraction.setActive(false) // 初始状态下禁用顶点编辑
  map.addInteraction(modifyInteraction)

  // 确保地图容器已渲染
  setTimeout(() => {
    map.updateSize()
  }, 0)
}

// 绘制禁飞区
const drawNoFlyZone = (area) => {
  if (area.coordinates.length > 0) {
    // 转换坐标顺序为[经度, 纬度]
    const coordinates = area.coordinates.map(coord => [coord[1], coord[0]])
    const polygon = new Polygon([coordinates])
    const vectorSource = map.getLayers().getArray()[1].getSource()
    const feature = new Feature({
      geometry: polygon,
      name: area.name
    })
    vectorSource.addFeature(feature)

    // 添加交互事件
    feature.on('change', () => {
      const updatedCoordinates = polygon.getCoordinates()[0]
      area.coordinates = updatedCoordinates.map(coord => [coord[1], coord[0]]) // 转换回[纬度, 经度]
      console.log('更新后的坐标:', area.coordinates)
    })
  }
}

// 在初始化地图后绘制禁飞区
onMounted(() => {
  if (!document.getElementById('map-container')) {
    console.error('地图容器未找到')
    return
  }
  try {
    initMap()
    areas.value.forEach(area => drawNoFlyZone(area))
  } catch (error) {
    console.error('地图初始化失败:', error)
  }
})

// 在组件卸载前销毁地图
onBeforeUnmount(() => {
  if (map) {
    map.setTarget(null)
    map = null
  }
})
</script>

<style lang="scss" scoped>
#map-container {
  width: 100%;
  height: 100%;
  z-index: 0;
}
</style>